package com.pig4cloud.pig.module.controller.charger;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.charger.Charger;
import com.pig4cloud.pig.module.api.entity.charger.ChargerPort;
import com.pig4cloud.pig.module.service.charger.IChargerPortService;
import com.pig4cloud.pig.module.service.charger.IChargerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 充电设备端口Controller
 *
 * @author ruoyi
 * @date 2022-05-07
 */
@Validated
@Api(value = "充电设备端口控制器", tags = {"充电设备端口管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/charger/port")
public class ChargerPortController {

    private final IChargerPortService chargerPortService;
    private final IChargerService chargerService;

    @Value("${ruoyi.profile}")
    private String uploadPath;

    @Value("${ruoyi.imgUrl}")
    private String imgUrl;


    /**
     * 查询充电设备端口列表
     */
    @ApiOperation("查询充电设备端口列表")
    @PreAuthorize("@pms.hasPermission('module:chargerport:list')")
    @GetMapping("/list")
    public TableDataInfo<ChargerPort> list(@Validated ChargerPort chargerPort) {
        QueryWrapper<ChargerPort> qw = new QueryWrapper<>();
        if(chargerPort.getChargerId()!=null){
            qw.eq("charger_id",chargerPort.getChargerId());
        }

        TableDataInfo<ChargerPort> td = PageUtils.buildDataInfo(chargerPortService.page(PageUtils.buildPage(),qw));
        List<ChargerPort> list = td.getData();
        for (ChargerPort chargerPort1 : list){

            if(StrUtil.isNotEmpty(chargerPort1.getQrCode())){
                chargerPort1.setQrCode(imgUrl + chargerPort1.getQrCode());
            }
        }
        return td;
    }

    /**
     * 获取充电设备端口详细信息
     */
    @ApiOperation("获取充电设备端口详细信息")
    @PreAuthorize("@pms.hasPermission('module:chargerport:query')")
    @GetMapping("/{id}")
    public R<ChargerPort> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        ChargerPort chargerPort = chargerPortService.getById(id);
        return R.ok(chargerPort);
    }


    /**
     * 重置二维码
     */
    @SysLog("重置二维码")
    @PostMapping("/resetQrCode")
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('module:chargerport:edit')")
    public R<Void> resetQrCode(@RequestBody ChargerPort chargerPort) {
        if(chargerPort.getId()!=null){
            try{
                chargerPort = chargerPortService.getById(chargerPort.getId());
                if(chargerPort != null){
                    Charger charger = chargerService.findById(chargerPort.getChargerId());
                    chargerPort.setChargerSn(charger.getChargerSn());
                    String port = String.format("%02d",chargerPort.getPortIndex());
                    String qrCode = "";
                    chargerPort.setChargerNum(charger.getChargerSn() + port);
                    String fileName = "device_qr_" + charger.getChargerSn() + port + ".jpg";
                    String content = "https://www.sdyuedou.com/wxmini/charger/qr?sn=" + charger.getChargerSn() + "&port=" + chargerPort.getPortIndex();
                    int upload_type = 0;//FileUploadUtils.TYPE_CHARGER;
                    System.out.println("content:  "+ content);
                    String img_key = "";//FileUploadUtils.getUploadPrefix(upload_type) + fileName;
                    QRCodeUtilEx.createQrCodeImg(content, "设备编号：" + charger.getChargerSn() + " "+ port + "端口",
						null, uploadPath +"/"+img_key, true, fileName, upload_type);
                    qrCode = img_key;
                    chargerPort.setQrCode(qrCode);
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (chargerPortService.updateById(chargerPort)) {
                return R.ok();
            }
        }
        return R.failed();
    }

    /**
     * 新增充电设备端口
     */
    @ApiOperation("新增充电设备端口")
    @PreAuthorize("@pms.hasPermission('module:chargerport:add')")
    @SysLog("充电设备端口")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody ChargerPort chargerPort) {
        return R.okByRow(chargerPortService.save(chargerPort) ? 1 : 0);
    }

    /**
     * 修改充电设备端口
     */
    @ApiOperation("修改充电设备端口")
    @PreAuthorize("@pms.hasPermission('module:chargerport:edit')")
    @SysLog("充电设备端口")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody ChargerPort chargerPort) {
        return R.okByRow(chargerPortService.updateById(chargerPort) ? 1 : 0);
    }

    /**
     * 删除充电设备端口
     */
    @ApiOperation("删除充电设备端口")
    @PreAuthorize("@pms.hasPermission('module:chargerport:remove')")
    @SysLog("充电设备端口")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(chargerPortService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
